﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CCPnuts.ISkyDiskFileSystem.Interfaces;
using CCPnuts.Pack;
using System.Threading;
using CCPnuts.ISkyDiskFileSystem;

namespace TestSkyDiskFileSystem
{
    abstract class Transmitor : PackedBase, I_Transmitor
    {
        public static int SendDelay = 1000;
        public static int SendCount = 5;

        public Transmitor(PackedInfo info)
            : base(info)
        {
            TransmissionState = TransmissionStateTypes.Stopped;
        }

        public Transmitor(PackedInfo info, SkyFile file)
            : this(info)
        {
            TotalToSend = file.Size;
            Sent = 0;
        }

        protected volatile bool NeedStop = false;

        #region I_Transmitor Members

        public event I_TransmissionUpdateEvent TransmissionUpdate;

        /// <summary>
        /// Gets the state of the transmission.
        /// </summary>
        public TransmissionStateTypes TransmissionState { get; set; }

        public virtual void Run()
        {
            NeedStop = false;
            TransmissionState = TransmissionStateTypes.Transmiting;
            Speed = (int)(TotalToSend * 1000.0 / SendCount / SendDelay);
            for (int i = 0; i < SendCount; i++)
            {
                Sent = (int)(TotalToSend * ((i + 1) * 1.0 / SendCount));
                Thread.Sleep(SendDelay);
                if (NeedStop)
                {
                    Sent = 0;
                    Speed = 0;
                    NeedStop = false;
                    TransmissionState = TransmissionStateTypes.Stopped;
                    return;
                }
                TransmissionUpdate();
            }
            Speed = 0;
            TransmissionState = TransmissionStateTypes.Finished;
        }

        public void Stop()
        {
            NeedStop = false;
        }

        public long TotalToSend { get; set; }

        public long Sent { get; set; }

        public int Speed { get; set; }

        #region Optional & Not implement

        public IAsyncResult BeginRun(AsyncCallback callback)
        {
            throw new NotImplementedException();
        }

        public void EndRun(IAsyncResult result)
        {
            throw new NotImplementedException();
        }

        public void Pause()
        {
            throw new NotImplementedException();
        }

        public void Resume()
        {
            throw new NotImplementedException();
        }

        #endregion

        #endregion
    }
}
